﻿using System;
using System.IO;
using System.Threading.Tasks;
using CnBlogsClient.Database;
using CnBlogsClient.Database.Models;
using SQLite;
using Xamarin.Forms;

[assembly: Dependency(typeof(Database))]
namespace CnBlogsClient.Database
{
    class Database : IDatabase
    {
        private SQLiteAsyncConnection _database;

        public Database()
        {
        }

        public void Initialize()
        {
            string dbPath = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData), "cnblogs.db");
            _database = new SQLiteAsyncConnection(dbPath);
            _database.CreateTableAsync<ClientCredentials>().Wait();
        }

        public ClientCredentials GetCredentialsAsync()
        {
            ClientCredentials clientCredentials = _database.Table<ClientCredentials>().FirstOrDefaultAsync().Result;
            return clientCredentials;
        }

        public bool SaveCredentialAsync(ClientCredentials clientCredentials)
        {
            _database.Table<ClientCredentials>().DeleteAsync();
            int count =  _database.InsertAsync(clientCredentials).Result;

            return count == 1 ? true : false; 
        }
    }
}
